<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :maskClosable="false"
    :footer="null"
    switchFullscreen
    :okButtonProps="{ class:{'jee-hidden': disableSubmit} }"
    @cancel="handleCancel"
    cancelText="关闭">

    <div>
      <a-row>
        <a-col :span="24">
          <a-form-model-item label="调拨日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="receiptsTime">
            <j-date placeholder="请选择调拨日期" v-model="model.allocateAndTransferTime" :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"/>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item label="调出仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="depositoryName">
            <a-select
              show-search
              placeholder="请选择调出仓库"
              option-filter-prop="children"
              v-model="model.outDepositoryId"
              style="width: 100%"
              :filter-option="filterOptionOutDepository"
              @focus="handleFocus"
              @blur="handleBlur"
              @change="changeDepository">
              <a-select-option :value="item.id" v-for="(item,index) in depositoryData" :key="index">
                {{item.depositoryName}}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item label="调入仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="depositoryName">
            <a-select
              show-search
              placeholder="请选择调入仓库"
              option-filter-prop="children"
              v-model="model.inDepositoryId"
              style="width: 100%"
              :filter-option="filterOptionInDepository"
              @focus="handleFocus"
              @blur="handleBlur">
              <a-select-option :value="item.id" v-for="(item,index) in depositoryData" :key="index">
                {{item.depositoryName}}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item label="操作" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="depositoryName">
            <a-button type="primary" style="margin-right: 10px" @click="submitSave(2)">提交审批</a-button>
            <a-button type="primary" @click="submitSave(1)">保存草稿</a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="depositoryName">
            <a-textarea
              v-model="model.remark"
              placeholder="请输入备注"
              :auto-size="{ minRows: 3, maxRows: 5 }"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
    </div>

    <div>
      <a-button class="editable-add-btn" @click="handleAdd" style="margin-bottom: 10px" >
        添加材料
      </a-button>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        class="j-table-force-nowrap"
        bordered
        :data-source="materialData"
        :columns="columns"
        :pagination="false"
        :rowKey="(record,index)=>{return index}"
      >
        <a slot="materialName" @click="showMaterialStock(record)" slot-scope="text,record">{{ text }}</a>
        <template v-for="col in ['allocateAndTransferNum','remark']" :slot="col"
                  slot-scope="text, record, index">
          <div :key="col" v-if="col != 'remark'">
            <a-input type="number"
              v-if="record.editable"
              style="margin: -5px 0"
              :value="text"
              @change="e => handleChange(e.target.value, record.key, col)"/>
            <template v-else>
              {{ text }}
            </template>
          </div>
          <div :key="col" v-if="col == 'remark'">
            <a-input
              v-if="record.editable"
              style="margin: -5px 0"
              :value="text"
              @change="e => handleChange(e.target.value, record.key, col)"/>
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template slot="operation" slot-scope="text, record, index">
          <div class="editable-row-operations">
            <span v-if="record.editable">
              <a @click="() => save(record.key)">保存</a>
            </span>
            <span v-else>
              <a :disabled="editingKey !== ''" @click="() => edit(record.key)">编辑</a>
            </span>
            <a-popconfirm title="确定删除这条记录吗" @confirm="() => onDelete(record.key)">
              <a>删除</a>
            </a-popconfirm>
          </div>
        </template>
      </a-table>
    </div>

    <select-material-modal ref="SelectMaterialModal" @ok="chooseMaterialOk($event)"></select-material-modal>
    <material-stock-modal ref="materialStockModal"></material-stock-modal>
  </j-modal>
</template>

<script>

  import {httpAction, getAction,deleteAction} from '@/api/manage'
  import {validateDuplicateValue} from '@/utils/util'
  import '@/assets/less/TableExpand.less'
  import selectMaterialModal from "../../purchaseOrder/modules/selectMaterialModal";
  import materialStockModal from "../../purchaseOrder/modules/materialStockModal";

  export default {
    name: 'allocateAndTransferModal',
    components: {
      selectMaterialModal,
      materialStockModal
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },

    data() {
      return {
        depositoryData: [],
        materialData:[],
        cacheData: [],
        editingKey: '',
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: '3%',
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '名称',
            dataIndex: 'materialName',
            width: '13%',
            align: "center",
            slots: { title: 'customTitle' },
            scopedSlots: { customRender: 'materialName' },
          },
          {
            title: '型号',
            dataIndex: 'modelNumber',
            width: '12%',
            align: "center",
            scopedSlots: {customRender: 'modelNumber'},
          },
          {
            title: '规格',
            dataIndex: 'specifications',
            width: '13%',
            align: "center",
            scopedSlots: {customRender: 'specifications'},
          },
          {
            title: '品牌',
            dataIndex: 'brand',
            width: '12%',
            align: "center",
            scopedSlots: {customRender: 'brand'},
          },
          {
            title: '单位',
            dataIndex: 'unit',
            width: '5%',
            align: "center",
          },
          {
            title: '市场价',
            dataIndex: 'marketPrice',
            width: '5%',
            align: "center",
            scopedSlots: {customRender: 'marketPrice'},
          },
          {
            title: '预算价',
            dataIndex: 'estimatedCost',
            width: '5%',
            align: "center",
            scopedSlots: {customRender: 'estimatedCost'},
          },
          {
            title: '成本价',
            dataIndex: 'costPrice',
            width: '5%',
            align: "center",
          },
          {
            title: '流转数量',
            dataIndex: 'allocateAndTransferNum',
            width: '8%',
            align: "center",
            scopedSlots: {customRender: 'allocateAndTransferNum'},
          },
          {
            title: '备注',
            dataIndex: 'remark',
            width: '12%',
            align: "center",
            scopedSlots: {customRender: 'remark'},
          },
          {
            title: '操作',
            dataIndex: 'operation',
            width: '8%',
            align: "center",
            scopedSlots: {customRender: 'operation'},
          },
        ],
        title: '',
        width: '90%',
        visible: false,
        disableSubmit: false,
        fullscreen: true,
        keyIndex: 0,
        addRowBeginIndex: 0,
        model: {},
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        confirmLoading: false,
        validatorRules: {},
        selectedRowKeys: [],
        selectedRows: [],
        depositoryMaterialStockData:[], //仓库材料库存数据
        currentDepositoryId: 0, //当前选中的仓库id
        url: {
          add: "/ghSupplychainAllocateAndTransfer/add",
          edit: "/ghSupplychainAllocateAndTransfer/edit",
          queryById: "/ghSupplychainAllocateAndTransfer/queryById",
          queryDepositoryList: "/ghSupplychainDepository/allList",
          queryAllocateAndTransferItemList: "/ghSupplychainAllocateAndTransferItem/list",
          deleteAllocateAndTransferItem: "/ghSupplychainAllocateAndTransferItem/delete",
          queryDepositoryMaterialStock: "/ghSupplychainDepositoryItem/queryStock",
        }
      }
    },
    computed: {
      formDisabled() {
        return this.disabled
      },
    },
    created() {
      //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      //查询库存并显示
      showMaterialStock(record){
        this.$refs.materialStockModal.title = "库存详情";
        this.$refs.materialStockModal.showMaterialStock(record);
      },
      //加载仓库
      loadDepositoryData(){
        getAction(this.url.queryDepositoryList).then((res) => {
          if (res.success) {
            this.depositoryData = res.result.records||res.result;
          }else{
            this.$message.warning(res.message)
          }
        })
      },
      changeDepository(value){
        this.currentDepositoryId = value;
        this.loadMaterialStock();
      },
      handleBlur() {
        console.log('blur');
      },
      handleFocus() {
        console.log('focus');
      },
      filterOptionOutDepository(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      filterOptionInDepository(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      handleChange(value, key, column) {
        const newData = [...this.materialData];
        const target = newData.find(item => key === item.key);
        if (target) {
          target[column] = value;
          this.materialData = newData;
        }
      },
      edit(key) {
        const newData = [...this.materialData];
        const target = newData.find(item => key === item.key);
        this.editingKey = key;
        if (target) {
          target.editable = true;
          this.materialData = newData;
        }
      },
      save(key) {
        const newData = [...this.materialData];
        const newCacheData = [...this.cacheData];
        const target = newData.find(item => key === item.key);
        const targetCache = newCacheData.find(item => key === item.key);

        if (target && targetCache) {
          delete target.editable;
          this.materialData = newData;
          Object.assign(targetCache, target);
          this.cacheData = newCacheData;
        }
        this.editingKey = '';
      },
      onDelete(key) {
        if(this.model.id){
          if (key <= this.addRowBeginIndex){
            let obj=this.materialData.find(function (obj) {
              return obj.key === key;
            })
            deleteAction(this.url.deleteAllocateAndTransferItem,{id:obj.id}).then(res=>{
              if (res.success){
                this.$message.success(res.message)
              }else {
                this.$message.warning(res.message)
              }
            })
          }
        }
        const data = [...this.materialData];
        this.materialData = data.filter(item => item.key !== key);
        this.editingKey = '';
      },
      handleAdd() {
        if(this.model.outDepositoryId == null) {
          this.$message.warning("请选择仓库")
          return;
        }

        this.$refs.SelectMaterialModal.title = "请选择材料";
        this.$refs.SelectMaterialModal.depositoryId = this.model.outDepositoryId;
        this.$refs.SelectMaterialModal.add();
      },

      chooseMaterialOk(arr){
        for (let i=0;i<arr.length;i++){
          arr[i].key = this.keyIndex;
          arr[i].materialId = arr[i].id;
          arr[i].id = null;
          this.materialData.push(arr[i]);
          this.cacheData.push(arr[i])
          this.keyIndex++;
        }
      },

      loadMaterialStock(){
        let params = {};
        params.depositoryId = this.currentDepositoryId;
        getAction(this.url.queryDepositoryMaterialStock,params).then((res) => {
          if (res.success) {
            this.depositoryMaterialStockData = res.result.records||res.result;
          }else{
            this.$message.warning(res.message)
          }
        })
      },

      addAllocateTransfer() {
        this.visible = true;
      },
      editAllocateTransfer(record) {
        this.model = Object.assign({}, record);
        this.currentDepositoryId = record.outDepositoryId;
        getAction(this.url.queryAllocateAndTransferItemList, {id:record.id}).then((res) => {
          if (res.success) {
            this.materialData = res.result.records||res.result;
            for (let i=0;i<this.materialData.length;i++){
              this.materialData[i].key = i.toString();
              this.cacheData.push(this.materialData[i]);
            }
            this.keyIndex = this.materialData.length;
            this.addRowBeginIndex = this.materialData[this.materialData.length-1].key;
          }else{
            this.$message.warning(res.message)
          }
        })
        this.loadMaterialStock();
        this.visible = true;
      },
      //提交审批，保存草稿
      submitSave(status){
        const that = this;
        if (this.model.outDepositoryId == null){
          this.$message.error("请选择出库仓库")
          return;
        }
        if (this.model.inDepositoryId == null){
          this.$message.error("请选择入库仓库")
          return;
        }
        if (this.model.outDepositoryId == this.model.inDepositoryId){
          this.$message.warning("调出仓库和调入仓库不能相同")
          return;
        }
        let httpurl = '';
        let method = '';
        if (this.materialData.length == 0){
          this.$message.warning("请至少添加一条有效数据")
          return;
        }else {
          if (!this.model.id) {
            httpurl += this.url.add;
            method = 'post';
          } else {
            httpurl += this.url.edit;
            method = 'put';
          }
        }
        for (let i=0;i<this.materialData.length;i++){
          if (this.materialData[i].allocateAndTransferNum == null || this.materialData[i].allocateAndTransferNum == 0){
            this.$message.warning("请输入【"+this.materialData[i].materialName+"】材料的数量")
            return;
          }else {
            if (this.materialData[i].allocateAndTransferNum < 0){
              this.$message.warning("【"+this.materialData[i].materialName+"】材料的数量输入有误")
              return;
            }
          }
        }
        //调拨需要判断库存数量
        if (status === 2){
          if (this.depositoryMaterialStockData.length === 0){
            this.$message.error("【"+this.materialData[0].materialName+"】库存不足")
            return;
          }
          for (let i=0;i<this.materialData.length;i++){
            let flag = false;
            for (let j=0;j<this.depositoryMaterialStockData.length;j++){
              if (this.materialData[i].materialId === this.depositoryMaterialStockData[j].materialId){
                flag = true;
                if (this.materialData[i].allocateAndTransferNum > this.depositoryMaterialStockData[j].stock){
                  this.$message.error("【"+this.materialData[i].materialName+"】库存不足")
                  return;
                }
              }
              //break;
            }
            if (!flag){
              this.$message.error("【"+this.materialData[i].materialName+"】库存不足"+"，当前仓库不存在该材料")
              return;
            }
          }
        }
        this.model.allocateAndTransferItemVos = this.materialData;
        this.model.status = status;

        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            that.$emit('ok');
            that.close();
          } else {
            that.$message.warning(res.message);
          }
        })
      },
      onClearSelected() {
        this.selectedRowKeys = [];
        this.selectionRows = [];
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectionRows
      },
      close() {
        this.$emit('close');
        this.visible = false;
        this.onClearSelected();
        this.materialData = [];
        this.cacheData = [];
        this.model = {};
        this.keyIndex = 0;
        this.editingKey = '';
      },
      handleCancel() {
        this.close()
      },

    }
  }
</script>
<style scoped>
  .editable-row-operations a {
    margin-right: 8px;
  }
  .tableHiddle {
    display: none;
  }
</style>